﻿using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Ipmce.RemoteVoting.Backend.DataAccess;
using Ipmce.RemoteVoting.Common.Tools;

namespace Ipmce.RemoteVoting.Backend.CountingApplication
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Length != 1)
			{
				Console.WriteLine("Usage: dump folder");
				return;
			}

			var dumpFolder = args[0];

			if (!Directory.Exists(dumpFolder))
			{
				return;
			}

			var files = Directory.GetFiles(dumpFolder);

			var decoder = new VoteEncryptor(new X509Certificate2(Resource.secret, "123"));


			using (var context = new RemoteVotingContext(ConfigurationManager.AppSettings["RemoteVotingDataBase"]))
			{
				foreach (var candidate in
					files.Select(file => decoder.Decrypt(File.ReadAllBytes(file))).Select(candidateId => context.Candidates.Find(candidateId.Id)))
				{
					candidate.VoteCount++;
				}

				context.SaveChanges();
			}
		}
	}
}
